package com.xrf;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.yunhe.cloud.kit.BizPacket;
import com.yunhe.cloud.kit.HttpRequestUtil;
import com.yunhe.cloud.kit.ReadConfig;
import com.yunhe.cloud.kit.SqlKit.PageInfo;
import com.yunhe.cloud.kit.StringKit;
import com.yunhe.cloud.model.Department;
import com.yunhe.cloud.model.Network;
import com.yunhe.cloud.model.Region;
import com.yunhe.cloud.model.Response;
import com.yunhe.cloud.model.Service;
import com.yunhe.cloud.model.ServiceConfig;
import com.yunhe.cloud.model.Template;
import com.yunhe.cloud.model.User;
import com.yunhe.cloud.model.UserServiceMapping;
import com.yunhe.cloud.pojo.RegionBean;
import com.yunhe.cloud.pojo.TemplateChildBean;
import com.yunhe.cloud.pojo.TemplateStatisticsResult;
import com.yunhe.cloud.service.DepartmentService;
import com.yunhe.cloud.service.NetworkService;
import com.yunhe.cloud.service.RegionService;
import com.yunhe.cloud.service.ServiceConfigService;
import com.yunhe.cloud.service.ServiceService;
import com.yunhe.cloud.service.TemplateService;
import com.yunhe.cloud.service.UserOperateService;
import com.yunhe.cloud.service.UserService;
import com.yunhe.cloud.service.UserServiceMappingService;
import java.util.Objects;

/**
 * 建筑工地考勤数据统计分析系统应用服务模块
 */
@Controller
@RequestMapping("service")
public class ServiceController extends BaseController {
    
    @Autowired
    ServiceService serviceService;
    
    @Autowired
    UserService userService;
    
    @Autowired
    DepartmentService departmentService;
    
    @Autowired
    TemplateService templateService;
    
    @Autowired
    RegionService rs;
    
    @Autowired
    UserOperateService us;
    
    @Autowired
    NetworkService ns;
    
    @Autowired
    ServiceConfigService ss;
    
    @Autowired
    UserServiceMappingService uss;
    
    @Autowired
    ReadConfig rc;
    
    public String cMarkInfoLikeName() {
        String templateName = getPara("templateName");
        List<Template> templeteList = new ArrayList<Template>();
        if(templateName != null || !templateName.equals(" ")){
            String templateSql = "SELECT template.*,(select t.`name` from template_type t where t.type = template.templateType) as typeName FROM template WHERE template.templateName LIKE"
                    + "'%" + templateName + "%'" + ";";
            if (!Objects.isNull(templateSql)) {
                templeteList = templateService.find(templateSql);
            }
        }
        return toJson(templeteList);
    }
    
    /**
     * 获取服务列表
     */
    @RequestMapping("list")
    @ResponseBody
    public String list(PageInfo pageInfo) {
        Service service = simpleModel(Service.class);
        Page<Service> page = serviceService.getPage(pageInfo, service);
        return toJson(page);
    }
    
    /**
     * 创建服务
     * 添加操作
     */
    @ResponseBody
    public String create(String serviceName, String userId, String remark,
            String templateId, String networkId, String configId,
            String networkName, String configName, String groupId,
            String groupName, String ip, String day) {
        
        User user = new User().findByIdLoadColumns(userId, "regionId");
        String regionId = user.getRegionId();
        
        String result = doCreate(serviceName, templateId, networkId, 
                configId, regionId, groupId, groupName, ip);
        Response response = gson.fromJson(result, mapType);
        
        if(!response.isSuccess()){
            return toJson(response);
        } else {
            if(ip == null && groupName == null){
                groupName = "default";
            }
            
            //3.创建成功后，用返回的虚拟机ID作为serviceId
            String serviceId = response.getResult();
            //4.将服务名称、serviceId、serviceName、regionId、templateId、serviceStatus(1)、remark构建为service表
            Service s = new Service().setId(serviceId).setServiceName(serviceName).setRegionId(regionId)
                    .setTemplateId(templateId).setRemarks(remark).set("securityGroup", groupName)
                    .set("networkId", networkId).set("configId", configId).setServiceStatus("9")
                    .set("useTime", day);
            boolean save2 = serviceService.save(s);
            if(!save2){
                throw new RuntimeException("创建服务失败");
            }
            //7.自动创建UUID为主键、通过userId和serviceId构建user_service_mapping表
            boolean save = uss.save(new UserServiceMapping().setId(UUID.randomUUID()+"").setServiceId(serviceId).setUserId(userId));
            if(!save){
                throw new RuntimeException("与用户关联服务失败");
            }
            StringBuffer sql = new StringBuffer(
                    serviceService.getSql("service.getServiceInfo"));
            Service findFirst = serviceService.findFirst(sql.toString(),
                    serviceId);
            return toJson(BizPacket.success().setResult(findFirst));
        }
    }
    
    // 需要实现 doCreate 方法
    private String doCreate(String serviceName, String templateId, String networkId, 
            String configId, String regionId, String groupId, String groupName, String ip) {
        // 实现创建逻辑
        return "";
    }
}